/**
 * Ajax请求
 * @param string url
 * @param object params
 * @param GET|POST type
 * @returns XMLHttp
 */
function toAjax(url,data,type){
    $.ajaxSetup({
        headers: {
            'X-XSRF-TOKEN': $.cookie('XSRF-TOKEN')
        }
    });
    var dom = $('<div></div>');
    var index = layer.load(1, {
        shade: [0.1,'#fff'] //0.1透明度的白色背景
    });
    var ajax = $.ajax({
        url:url,
        data:data,
        type:type,
        success:function (data, textStatus) {
            if(data.code == 1){
                dom.trigger('hxop.ajax-success',data.data, textStatus);
            }else{
                parent.layer.alert('失败!失败原因:' + data.message);
                dom.trigger('hxop.ajax-failed',data.data,textStatus)
            }
        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
            parent.layer.alert('失败!错误:' + textStatus);
            dom.trigger('hxop.ajax-error',XMLHttpRequest, textStatus,errorThrown);
        },
        complete:function(XMLHttpRequest, textStatus){
            layer.close(index);
            dom.trigger('hxop.ajax-complete',XMLHttpRequest, textStatus);
        }
    });
    return {
        abort:ajax.abort,
        on:function(){
            dom.on.apply(dom,arguments);
            return this;
        },
        off:function(){
            dom.off.apply(dom,arguments);
            return this;
        },
        one:function(){
            dom.one.apply(dom,arguments);
            return this;
        }
    };
}

var uniqueId = (function(){
    var count = 0;
    return function(){
        return count++;
    }
})();

/**
 * 解析url
 *@param {string} url 完整的URL地址
 *@returns {object} 自定义的对象
 *@description 用法示例：var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
 myURL.file='index.html'

 myURL.hash= 'top'

 myURL.host= 'abc.com'

 myURL.query= '?id=255&m=hello'

 myURL.params= Object = { id: 255, m: hello }

 myURL.path= '/dir/index.html'

 myURL.segments= Array = ['dir', 'index.html']

 myURL.port= '8080'

 myURL.protocol= 'http'

 myURL.source= 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'

 */
function parseURL(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: function(){
            var arr = [];
            $.each(this.params,function(k,v){
                arr.push(k + '=' + v);
            });
            return arr.join('&');
        },
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/'),
        addParam:function(k,v){
            this.params[k] = v;
        },
        pack:function(){
            var url = '';
            if(this.host){
                url += this.protocol + '://' + this.host;
                if(this.port){
                    url += ':' + this.port;
                }
            }
            if(this.path){
                url += this.path;
            }
            var paramstr = this.query();
            if(paramstr.length > 0){
                url += '?' + paramstr;
            }
            return url;
        }
    };
}
var pager = {
    goPage:function(el,page){
        var url = parseURL($(el).parent().data('path'));
        url.addParam('page',page);
        href = url.pack();
    },
};

function go_page(url,params){
    var p = [];
    $.each(params,function(k,v){
        p.push(k + '=' + v);
    });
    if(p.length > 0){
        url += '?' + p.join('&');
    }
    location.href = url;
}

function setDateRange(start,end){
    $(start).on('change',initDate).datepicker({
        startView: 1,
        todayBtn: "linked",
        keyboardNavigation: false,
        forceParse: false,
        autoclose: true,
        format: "yyyy-mm-dd"
    });
    $(end).on('change',initDate).datepicker({
        startView: 1,
        todayBtn: "linked",
        keyboardNavigation: false,
        forceParse: false,
        autoclose: true,
        format: "yyyy-mm-dd"
    });

    var start = $('input[name=start_date]');
    var end = $('input[name=end_date]');
    var pStart = start.data('datepicker');
    var pEnd = end.data('datepicker');

    function initDate(){
        var sDate = pStart.getDate();
        var eDate = pEnd.getDate();
        pStart.setEndDate(eDate);
        pEnd.setStartDate(sDate);
    }
}

function mkmap(src,column){
    var o = {};
    $.each(src,function(k,v){
        if(column === undefined && typeof(v) != 'object'){
            o[v] = v;
        }else{
            o[v[column]] = v;
        }
    });
    return o;
}

function flip(arr){
    var o = {};
    $.each(arr,function(k,v){
        o[v] = k;
    });
    return o;
}

function groupby(src,column){
    var o = {};
    $.each(src,function(k,v){
        var key = v[column];
        if(key in o){
            o[key].push(v);
        }else{
            o[key] = [v];
        }
    });
    return o;
}

function cp(src,columns){
    var o = {};
    $.each(columns,function(k,v){
        o[v] = src[v];
    });
    return o;
}
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt)
{ //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
Date.Format = function (timestamp, fmt) {
    var date = new Date();
    date.setTime(timestamp);
    return date.Format(fmt);
};